package self

import (
	"GraduationProject/public/db"
	"GraduationProject/public/models"
	"GraduationProject/webserver/controllers/util"
	"database/sql"
	"github.com/gin-gonic/gin"
)

// todo: 修改个人信息
func SetSelfData(c *gin.Context) {
	user, err := util.UserFilter(c)
	if err != nil {
		return
	}

	password := c.PostForm("password")
	nickname := c.PostForm("nickname")
	phone := c.PostForm("phone")

	updateMap := make(map[string]interface{})
	if password != "" {
		updateMap["password"] = util.Sha256(password)
	}
	if nickname != "" {
		updateMap["nickname"] = nickname
	}
	if phone != "" {
		updateMap["phone"] = phone
	}

	if db.DB.Model(&models.User{}).Where("id = ?", user.ID).
		Updates(updateMap).Error == sql.ErrConnDone {
		util.FailedResponse(c, 10001, "修改失败")
		return
	}

	util.SuccessResponse(c)
}

// todo: 修改头像Url
func SetAvatarUrl(c *gin.Context) {
	user, err := util.UserFilter(c)
	if err != nil {
		return
	}

	avatarUrl := c.PostForm("avatar")
	if avatarUrl == "" {
		util.FailedResponse(c, 10001, "头像url不能为空")
		return
	}

	if db.DB.Model(&models.User{}).Where("id = ?", user.ID).
		Update("avatar", avatarUrl).RowsAffected == 0 {
		util.FailedResponse(c, 10001, "更新头像失败")
		return
	}

	util.SuccessResponse(c)
}

// todo: 修改密码
func SetPassword(c *gin.Context) {
	user, err := util.UserFilter(c)
	if err != nil {
		return
	}

	oldPassword := c.PostForm("old_password")
	newPassword := c.PostForm("new_password")
	newPasswordRepeat := c.PostForm("new_password_repeat")
	if oldPassword == "" || newPassword == "" || newPasswordRepeat == "" {
		util.FailedResponse(c, 10001, "密码不能为空")
		return
	}

	if newPassword != newPasswordRepeat {
		util.FailedResponse(c, 10002, "重复密码不一致")
		return
	}

	if user.Password != util.Sha256(oldPassword) {
		util.FailedResponse(c, 10003, "密码错误")
		return
	}

	if db.DB.Model(&models.User{}).Where("id = ?", user.ID).
		Update("password", util.Sha256(newPassword)).RowsAffected == 0 {
		util.FailedResponse(c, 10004, "修改密码失败")
		return
	}

	util.SuccessResponse(c)
}
